package com.yumeng.framework.auth.security.userdetails;

import com.yumeng.common.auth.BaseAuthInfo;
import com.yumeng.framework.auth.security.bean.MyUserDetails;
import com.yumeng.framework.auth.service.auth.NormalAuthService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsPasswordService;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

/**
 * @author wxd
 * @date 2024/7/22 下午4:30
 */
public class NormalUserDetailsServiceImpl extends MyAbstractUserDetailsService implements UserDetailsService, UserDetailsPasswordService {

    private final NormalAuthService normalAuthService;

    public NormalUserDetailsServiceImpl(NormalAuthService normalAuthService) {
        super(normalAuthService);
        this.normalAuthService = normalAuthService;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        return super.getUserDetailsByPrincipal(username);
    }

    @Override
    public UserDetails updatePassword(UserDetails user, String newPassword) {
        boolean b = normalAuthService.updateCredentials(user.getUsername(), newPassword);
        if (b){
            if (user instanceof MyUserDetails myUserDetails) {
                myUserDetails.setPassword(newPassword);
            }
        }
        return user;
    }

    @Override
    protected BaseAuthInfo retrieveBaseAuthInfo(Object principal) {
        return normalAuthService.findByAuthKey((String) principal);
    }
}
